package com.thesis.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.thesis.manage.common.controller.AbstractController;
import com.thesis.manage.common.exception.CommonException;
import com.thesis.manage.common.utils.Result;
import com.thesis.manage.domain.Admin;
import com.thesis.manage.feign.UserService;
import com.thesis.manage.service.model.RoleEnum;
import com.thesis.manage.service.model.StateCodeEnum;
import com.thesis.manage.service.module.dto.LoginDTO;
import com.thesis.manage.service.module.dto.UserLoginDTO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author php
 * @date 2018/2/1
 */
@RestController
@RequestMapping("/user")
public class LoginController extends AbstractController {
    @Resource
    private UserService userService;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody LoginDTO loginDTO) {
        return buildMessage(() -> {
            Result result = userService.login(loginDTO.getUsername(), loginDTO.getPassword(), RoleEnum.ADMIN.getValue());
            UserLoginDTO userLoginDTO;
            if (result != null && result.getStatus() == StateCodeEnum.SUCCESS.getValue().intValue()) {
                Object data = result.getData();
                userLoginDTO = JSONObject.parseObject(data.toString(), UserLoginDTO.class);
                Admin admin = JSONObject.parseObject(userLoginDTO.getUserInfo(), Admin.class);
                userLoginDTO.setUserInfo(admin.getName());
            } else {
                throw new CommonException("login.failed", "用户名或密码错误");
            }
            return userLoginDTO;
        });
    }

    @DeleteMapping("/logout")
    public Map<String, Object> logout(String token) {
        return buildMessage(() -> {
            userService.logout(token);
            return null;
        });
    }

    @GetMapping("/info")
    public Map<String, Object> info() {
        return buildMessage(() -> {
            String token = getToken();
            Result result = this.userService.findUserByToken(token);
            return JSONObject.parseObject(result.getData().toString(), Admin.class);
        });
    }
}
